using DeleteOnTimeTool.Models;

namespace DeleteOnTimeTool.Services
{
    public static class DeleteService
    {
        public static int Execute(AppConfig config)
        {
            int totalDeleted = 0;
            foreach (var task in config.Tasks.Where(t => t.Enabled))
            {
                try
                {
                    totalDeleted += ExecuteTask(config, task);
                }
                catch (Exception ex)
                {
                    LogService.WriteError(config, $"任务 '{task.Name}' 失败: {ex.Message}");
                }
            }
            LogService.WriteInfo(config, $"执行完毕，删除文件总计: {totalDeleted}");
            return totalDeleted;
        }

        private static int ExecuteTask(AppConfig config, DeleteTask task)
        {
            if (string.IsNullOrWhiteSpace(task.Path) || !Directory.Exists(task.Path))
            {
                LogService.WriteError(config, $"任务 '{task.Name}' 路径无效: {task.Path}");
                return 0;
            }

            DateTime? beforeDate = task.DeleteBeforeDate;
            if (beforeDate == null && task.OlderThanDays > 0)
            {
                beforeDate = DateTime.Now.AddDays(-task.OlderThanDays);
            }
            if (beforeDate == null)
            {
                LogService.WriteError(config, $"任务 '{task.Name}' 未设置有效的删除日期条件");
                return 0;
            }

            var option = task.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            var pattern = string.IsNullOrWhiteSpace(task.SearchPattern) ? "*" : task.SearchPattern;
            int deleted = 0;

            foreach (var file in Directory.EnumerateFiles(task.Path, pattern, option))
            {
                try
                {
                    DateTime fileTime = task.Basis == TimeBasis.CreatedTime
                        ? File.GetCreationTime(file)
                        : File.GetLastWriteTime(file);

                    if (fileTime <= beforeDate.Value)
                    {
                        File.Delete(file);
                        deleted++;
                        LogService.WriteInfo(config, $"删除: {file} (时间: {fileTime:yyyy-MM-dd HH:mm:ss})");
                    }
                }
                catch (Exception ex)
                {
                    LogService.WriteError(config, $"删除失败: {file} - {ex.Message}");
                }
            }

            LogService.WriteInfo(config, $"任务 '{task.Name}' 完成，删除文件: {deleted}");
            return deleted;
        }
    }
}


